let expess = require('express');
let router = expess.Router()
let fs = require('fs');
let path = require('path');
let mgdb = require('../../utils/mgdb')
let bcrypt = require('../../utils/bcrypt')

router.post('/', (req, res, next) => {




  //获取 username,password,nikename,icon

  let { username, password, nikename } = req.body;

  //必传参数
  if (!username || !password) {
    res.send({ err: 1, msg: '用户名密码必传' });
    return;
  }

  //系统生成 time fans follow nikename
  // nikename = nikename || '系统自带生成';//npm 找包来生成
  nikename = username;//npm 找包来生成
  let follow = 0;
  let fans = 0;
  let time = Date.now()

  let icon = '/upload/default.jpg';



  //判断是否传头像
  if (req.files && req.files.length > 0) {
    //改名
    fs.renameSync(
      req.files[0].path,
      req.files[0].path + path.parse(req.files[0].originalname).ext
    )

    //覆盖默认
    icon = '/upload/user/' + req.files[0].filename + path.parse(req.files[0].originalname).ext
  }



  //兜库 username不能重，password需要加密入库, 注册失败删除头像
  //开库
  mgdb.open({
    collectionName: 'user'
  }).then(
    ({ collection, client }) => {
      //查询
      collection.find({ username }).toArray((err, result) => {
        if (err) {
          res.send({ err: 1, msg: '结合操作失败' })
          client.close()
        } else {
          console.log(0)
          if (result.length === 0) {

            //插入，入库，增,password需要加密
            password = bcrypt.hashSync(password);

            collection.insertOne({
              username, password, nikename, fans, follow, time, icon
            }, (err, result) => {

              if (!err) {
                res.send({ err: 0, msg: '注册成功', data: { _id: result.insertedId, nikename, fans, follow, time, icon } })
              } else {
                res.send({ err: 1, msg: "注册失败，请重试" })
              }

            })

          } else {
            if (!icon.includes('default')) {
              fs.unlinkSync('./public' + icon);//子路由被主路由引入，网络作用域在app.js的位置
            }

            res.send({ err: 1, msg: '用户已存在' })
            client.close()

          }
        }
      })
    }
  )



})

module.exports = router;